<?php

namespace App\Http\Controllers;   //命名空间的三元素：常量，方法，类

use App\article;
use App\comment;
use function foo\func;
use Illuminate\Http\Request;
use Input;
use Illuminate\Support\Facades\DB; //引入DB门面
use App\Member; //引入模型
use Illuminate\Support\Facades\Session; //引入session
use Illuminate\Support\Facades\Cache;  //引入cache

class TestController extends Controller
{
    //
    public function test1()
    {
        phpinfo();

    }

    //测试input获取数据
    public function test2()
    {
        //获取一个值，没有则获取10086
        echo Input::get('id','10086').'<br>';
        //获取全部值，返回数组
//        dd(Input::all());  //laravel内置函数，=var_dump()+die():输出数组并停止执行下面语句
        //获取指定信息，字符串
        echo Input::get('name');
        //获取指定的值，返回数组
//        dd(Input::only(['name','id']));
        //获取除了指定值外的值,返回数组
//        dd(Input::except(['name']));
        //判断某个值是否存在，返回boolean
//        dd(Input::has('gender'));
        //
    }
//数据库操作
    public function add(){

        $db = DB::table('member');
//        $result = $db->insert([
//            [
//                'name' => '张三',
//                'age' => 18,
//                'email' => 'asd@qq.com'
//            ],
//            [
//                'name' => '李四',
//                'age'  => 19,
//                'email' => 'asd@qq.com'
//             ]
//        ]);
        $result = $db->insertGetId([
           'name' => '王五',
           'age'  => 20,
            'email' => 'adwqe@qq.com'
        ]);

        echo $result;
    }
    public function del(){
        $db = DB::table('member');

        $data = $db->get();
        $db->where('id','=','5')->delete();
        foreach ($data as $key => $value){
           echo "{$value -> id}, {$value -> name}, {$value -> age}, {$value -> email} <br>";
        }

    }
    public function update(){
        $db = DB::table('member');
        $result = $db -> where('id','<','3') -> update([
            'name' => '占三分',
            'age' => 23
        ]);
        echo ($result);

        $db -> increment('age',6);
        $db -> decrement('age',4);
    }
    public function sel(){
        $db = DB::table('member');
//        $data = $db->get();  //获取整个表数据，返回集合,每条记录是一个对象，不是数组
//        foreach ($data as $key => $value){
//           echo "{$value -> id}, {$value -> name}, {$value -> age}, {$value -> email} <br>";
//        }
//        // 条件查询
//        $data1 = $db->where('id','<','3')->get();
//        foreach ($data1 as $key => $value){
//           echo "{$value -> id}, {$value -> name}, {$value -> age}, {$value -> email} <br>";
//        }
//        $data2 = $db->where('id','<','3')->where('age','<','29')->get();
//        foreach ($data2 as $key => $value){
//           echo "{$value -> id}, {$value -> name}, {$value -> age}, {$value -> email} <br>";
//        }
//        $data3 = $db->where('id','<','3')->orwhere('age','<','25')->get();
//        foreach ($data3 as $key => $value){
//            echo "{$value -> id}, {$value -> name}, {$value -> age}, {$value -> email} <br>";
//        }
//
//        $data4 = $db->where('id','3')->first();
//        echo $data4 -> id.$data4 -> name.$data4 -> age.$data4 -> email."<br>";
//
//        $data5 = $db->where('id','3')->value('name');
//        echo $data5."<br>";
//
//        $data6 = DB::table('member')->select('name','email')->get();  //上面的操作对db产生了影响，
//        dd($data6);
//
//        $data7 = DB::table('member')->orderBy('age','desc')->get();   //同时查询操作太多，结果不显示
//        dd($data7);

        $data8 = $db -> limit(2) -> offset(1) -> get();
        dd($data8);

    }
    public function test3(){
        $date = date('Y-m-d H:i:s',time());

        $day = '日';

        $time = strtotime('+1 year');
//        return view('home/test/test3',['date' => $date,'day' => $day]);   //优先*.blade.php,否则*.php
        return view('home/test/test3',compact('date','day','time'));  //compact,php内置打包数组函数
    }

    public function test4(){
        $data = DB::table('member') ->get();
        $day = date('N');
        return view('home.test.test4',compact('data','day'));
    }

    public function test5(Request $request){   //利用request对象
        $result = $request -> input('title');
        echo $result;
    }

    public function test6(){
        return view('home.test.child');
    }
    public function test7(){
        return view('home.test.csrf');
    }


//    模型操作 ，两种方式
//1、静态使用，不需要实例化 等价于DB::table()->操作；2、实例化模型再去使用模型类

//AR模式，必须要实例化模型
public function mAdd(Request $request){
        $model = new Member();
//        $model -> name = '钱七';
//        $model -> age = 18;
//        $model -> email = 'qpewip@qq.com';
//        $model -> save(); //返回boolean值
        //request方法保存表单数据

        $model::create($request->all()); //使用这个必须定义fillable属性，允许写入字段


}

public function mSel(){
//        $data = Member::find(1);  //返回对象
    //查询符合条件的第一条记录
//        $data = Member::where('id','<','5') -> first(); //返回对象
//        $data = Member::all(['name','age','email']);
          $data = Member::where('id','<','7')->get(['name','age','email']);  //和all()不同的是，all不能够连接where方法

          dd($data);   //转换为数组
}

//AR模式，修改前需要去查询
public function mUpdate(){
        $model = Member::find(1);
        $model -> email = 'asddas@qq.com';

        $model -> save();
}
//AR模式，先查询后删除
public function mDel(){
        $model = Member::find(8);

        $model -> delete();
}

//自动验证+验证码
public function val(Request $request){
    if (Input::method() == 'POST'){    //一定是大写的POST
        $this -> validate($request,[
            //具体的验证规则
           'name' => 'required|min:2|max:20',
            'age' => 'required|integer|min:1|max:100',
            'email' => 'required|email',
            'captcha' => 'required|captcha',
        ]);

    }else{
        return view('home.test.validation');
    }
}
//文件上传
    public function fileUpload(Request $request){
        if (Input::method() == 'POST'){
//            dd($_FILES);  //状态码：0～7

        //判断文件是否正常
        if ($request -> hasFile('avatar') && $request -> file('avatar') -> isValid()){
            //获取文件原始名称
            $file = $request -> file('avatar') ;
            $fileName = $file -> getClientOriginalName(); //获取文件名
            $fileSize = $file -> getClientSize(); //获取大小
            $fileExt = $file -> getClientOriginalExtension(); //获取扩展名
//            dd($fileName.$fileSize);

            //移动文件
            $file -> move('./uploads',time().'.'.$fileExt);
            $data = $request -> all();

            $data['avatar'] = './uploads/'.time().'.'.$fileExt;  //新建字段要去模型文件开启字段写入
            $result = Member::create($data);
//            dd($result);
            if($result){
                return redirect('/');  //跳转响应
            }
        }

        }else{
            return view('home.test.fileUpload');
        }
    }
    //数据分页
    public function page(){
//        $data = Member::get();
        $data = Member::paginate(2);   //分页

        return view('home.test.page',compact('data'));
    }

    //ajax响应，bool值不能被直接响应
    public function ajax(){

        $data = Member::all();
        //响应处理
//        return json_encode($data);  //php原生
        return response()->json($data); //laravel框架
    }
    //会话控制
    public function sess(){
        Session::put('name','张三');
        echo Session::get('name').'<br>';
        echo Session::get('nam','李四').'<br>';
        echo Session::get('nam',function (){
            return 'ww';
            }).'<br>';

        echo Session::has('name').'<br>';
        dump(Session::all());
        Session::forget('name'); //删除一个session
        Session::flush(); //删除全部
    }

    //缓存操作
    public function cache(){
        Cache::put('name','张三',10);
        Cache::put('name','李四',10);
        Cache::add('name','李四',10);
        Cache::forever('name1','王五');
        echo Cache::get('name');  //获取方法同session

        Cache::add('age','15',10);
//        Cache::increment('age');
//        Cache::decrement('age');
        //设置默认时间
        $value = Cache::remember('time',100,function (){
            return date('y-m-d H:m:s',time());
        });

        dump(Cache::has('time'));
        dump($value);
    }

    //联表查询
    public function TATSel(){
        $res = DB::table('article as t1') -> select('t1.id','t1.article_name','t2.author_name')
            -> leftJoin('author as t2','t1.author_id', '=', 't2.id') -> get();
        dump($res);

    }

    //关联模型（一对一）

    public function oneToOne(){
        $data = article::get();  //返回对象

        foreach ($data as $key => $value){
            echo $value ->id ." ". $value -> article_name ." ".$value ->author -> author_name."<br>";
        }
    }
    //一对多
    public function oneToMany(){
        $data = article::get();
        foreach ($data as $key => $value){
            echo  '文章名称：'.$value -> article_name ."<br>";
            foreach ($value -> comment as $k => $val){
                echo '文章评论：'.$val -> comment."<br>";
            }
        }
    }
    //多对多,不需要给关系表创建模型
    public function manyToMany(){
        $data = article::get();
        foreach ($data as $key => $value){
            echo  '文章名称：'.$value -> article_name ."<br>";
            foreach ($value -> keyWord as $k => $val){
                echo '关键词：'.$val -> keyWord."<br>";
            }
        }
    }
}
